﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using Common.Utilities;
using Common.Utilities.Dispatcher;
using Common.Utilities.NetworkUtilities;

namespace Workflows.Components.ETL
{
    /// <summary></summary>
    public class BFileUploadWorker:IWorker
    {
        private Thread workerThread;
        private BFileUploadInstruction instruction;
        private BFileUploadOutput output;
        private RunContext context;
        private Guid _JobTicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary></summary>
        public Thread WorkerThread
        {
            get { return workerThread; }
        }
        /// <summary></summary>
        public InstructionBase Instruction
        {
            get { return instruction; }
        }
        /// <summary></summary>
        public ResultBase Output
        {
            get { return output; }
        }
        /// <summary></summary>
        public Type ComponentType
        {
            get { return typeof(BFileUploadComponent); }
        }
        /// <summary></summary>
        public RunContext Context
        {
            get { return context; }
            set { context = value; }
        }
        /// <summary></summary>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this.instruction = (BFileUploadInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this.instruction = (BFileUploadInstruction)request;
            this.context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void DoWork()
        {
            if(this.WorkerStartedEvent !=null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this.instruction);
            }

            this.workerThread = Thread.CurrentThread;
            this.UploadFilesToDb();
        }
        /// <summary></summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this.instruction);
            }

            this.workerThread = new Thread(new ThreadStart(this.UploadFilesToDb));
            this.workerThread.Start();
        }
        /// <summary></summary>
        public void CancelWork()
        {
            if(this.workerThread !=null && this.workerThread.IsAlive)
            {
                this.workerThread.Abort();
                this.workerThread.Join();

                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._JobTicketID, this.GetType(), this.instruction);
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;


        #region upload
        private void UploadFilesToDb()
        {
            SqlConnection conn=new SqlConnection(this.instruction.ConnStr);
            string logFilePath = Path.Combine(this.instruction.SrcFolderPath, "BFileUpload.log");
            if (File.Exists(logFilePath))
            {
                File.Delete(logFilePath);
            }
            string errorFilePath = Path.Combine(this.instruction.SrcFolderPath, "BFileUpload.err");
            if (File.Exists(errorFilePath))
            {
                File.Delete(errorFilePath);
            }
            StreamWriter logWriter = new StreamWriter(logFilePath);
            StreamWriter errWriter = new StreamWriter(errorFilePath);

            try
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();

                
                FileInfo[] files = null;
                if(string.IsNullOrEmpty(this.instruction.Filter))
                {
                    this.instruction.Filter = "*.*";
                }
                DirectoryInfo dirInfo=new DirectoryInfo(this.instruction.SrcFolderPath);
                if(this.instruction.IncludeSubFolder)
                {
                    files = dirInfo.GetFiles(this.instruction.Filter, SearchOption.AllDirectories);
                }
                else
                {
                    files = dirInfo.GetFiles(this.instruction.SrcFolderPath, SearchOption.TopDirectoryOnly);
                }
                if(files ==null || files.Length==0)
                {
                    throw new Exception("Unable to find any files");
                }

                int totalFileToDo = files.Length;
                int totalFileScanned = 0;
                int totalFileUploaded = 0;

                TableColumn imgCol =
                    DbUtil.GetTableColumn(this.instruction.ConnStr, this.instruction.TableName, this.instruction.ImageFieldName);
                TableColumn fileNameCol =
                    DbUtil.GetTableColumn(this.instruction.ConnStr, this.instruction.TableName,
                                          this.instruction.FileNameField);
                TableColumn pathCol =
                    DbUtil.GetTableColumn(this.instruction.ConnStr, this.instruction.TableName,
                                          this.instruction.FilePathField);
                string spName = "BfileUpload_" + this.instruction.TableName;

                string dropSql = StoredProcUtil.CreateDropStoredProcedureStatement(DataProviderType.MSSQL, spName);
                cmd.CommandText = dropSql;
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();

                string createSpSql =
                    StoredProcUtil.CreateStoredProcedureStatementForInsert(DataProviderType.MSSQL, spName,
                                                                           string.Empty, this.instruction.TableName,
                                                                           new TableColumn[]
                                                                               {fileNameCol, pathCol, imgCol});
                cmd.CommandText = createSpSql;
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();

                SqlParameter imgParam=new SqlParameter("@"+this.instruction.ImageFieldName,null);
                SqlParameter fileNameParam=new SqlParameter("@"+this.instruction.FileNameField,null);
                SqlParameter filePathParam=new SqlParameter("@"+this.instruction.FilePathField,null);

                foreach(FileInfo file in files)
                {
                    try
                    {
                        bool upload = true;
                        if (this.instruction.KeyFieldName != null &&
                            this.instruction.KeyFieldName == this.instruction.FileNameField)
                        {
                            bool exist = false;
                            cmd.CommandText = "select count (*) from " + this.instruction.TableName +
                                              " where " + this.instruction.FileNameField + "='" + file.Name + "'";
                            cmd.CommandType = CommandType.Text;
                            try
                            {
                                int countExist = int.Parse(cmd.ExecuteScalar().ToString());
                                if (countExist > 0)
                                {
                                    exist = true;
                                }
                            }
                            catch
                            {
                                exist = false;
                            }
                            if (exist)
                            {
                                upload = false;
                            }
                        }
                        if (upload)
                        {
                            fileNameParam.Value = file.Name;
                            filePathParam.Value = NetworkShareMap.getUNCPath(file.FullName);
                            BinaryReader reader = new BinaryReader(File.OpenRead(file.FullName));
                            byte[] contents = new byte[file.Length];
                            reader.Read(contents, 0, contents.Length);
                            imgParam.Value = contents;

                            cmd.CommandText = spName;
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddRange(new SqlParameter[] {fileNameParam, filePathParam, imgParam});
                            cmd.ExecuteNonQuery();

                            reader.Close();
                            totalFileUploaded++;
                        }

                        logWriter.WriteLine("{0}: Uploaded {1}", DateTime.Now.ToString(), file.Name);
                    }
                    catch(Exception ex1)
                    {
                        if(this.WorkerErredEvent !=null)
                        {
                            this.WorkerErredEvent(this._JobTicketID, this.GetType(), this.instruction, ex1.ToString(),true);
                            errWriter.WriteLine("{0}: {1} {2}", DateTime.Now.ToString(), file.Name, ex1.ToString());
                            errWriter.Flush();
                        }
                    }

                    totalFileScanned++;

                    if(this.WorkerStatusChangedEvent !=null && totalFileScanned %10==0)
                    {
                        string msg =
                            string.Format("Scanning {0} of {1} files, {2} files uploaded.", totalFileScanned,
                                          totalFileToDo, totalFileUploaded);
                        int percent = (totalFileScanned*100)/totalFileToDo;
                        this.WorkerStatusChangedEvent(this._JobTicketID, this.GetType(), this.instruction,
                            this.WorkflowName, this.ComponentName, msg, percent);
                    }
                }

                this.output=new BFileUploadOutput(this.instruction.OwnerComponentID,this._JobTicketID,totalFileUploaded,logFilePath,errorFilePath);
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._JobTicketID, this.GetType(), this.instruction, this.output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._JobTicketID, this.GetType(), this.instruction, ex.ToString(),true);
                }
            }
            finally
            {
                conn.Close();
                logWriter.Close();
                errWriter.Close();
            }
        }
        #endregion
    }
}
